import { apiGetWeathers } from '@/api/index'

export default {
  namespaced: true,
  state: {
    data: {
      city: '',
      // 更新时间
      date_time: '',
      // pm2.5数据
      'pm2.5': {},
      // 实时数据
      realtime: {},
      // 指数
      indexes: [],
      // 天气预报
      weathers: []
    }
  },
  mutations: {
    SET_DATA(state, data) {
      Object.assign(state.data, data)
    }
  },
  actions: {
    async getWhether({ commit }, city) {
      try {
        const data = await apiGetWeathers({ city })
        
        const updateData = {
          city: data.city,
          date_time: data.date_time,
          'pm2.5': data.info['pm2.5'],
          realtime: data.info.realtime,
          indexes: data.info.indexes,
          weathers: data.info.weathers
        }
        commit('SET_DATA', updateData)
      } catch (err) {
        console.error('获取天气数据失败', err) 
        uni.showModal({
          title: '获取天气数据失败',
          content: err.message,
        })
      }
    }
  }
}